package com.ulook.lookplanet.ui.notifications.chat;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.util.Log;

import androidx.lifecycle.LiveData;
import androidx.lifecycle.MutableLiveData;

import com.ulook.lookplanet.base.BaseViewModel2;
import com.ulook.lookplanet.common.AppServer;
import com.ulook.lookplanet.data.model.TUser;
import com.ulook.lookplanet.ui.notifications.VMsgUser;
import com.ulook.lookplanet.util.StringUtil;
import com.ulook.lookplanet.util.TimeUtil;
import com.ulook.lookplanet.util.net.AsynRequestUtil;
import com.ulook.lookplanet.util.net.OkHttpException;
import com.ulook.lookplanet.util.net.RequestParams;
import com.ulook.lookplanet.util.net.ResponseCallback;

import org.litepal.LitePal;

import java.util.List;
import java.util.UUID;

/**
 * 描述：
 *
 * @author L1998
 * @data 2021/5/8
 */
public class ChatViewModel extends BaseViewModel2 {

    private VMsgUser msgUser;
    private MutableLiveData<Boolean> initState = new MutableLiveData<>();  // 数据初始换成信号
    private Bitmap youHead;
    private Bitmap myHead;
    private volatile boolean you = false;
    private volatile boolean me = false;

    public LiveData<Boolean> getInitState(){
        return initState;
    }

    public Bitmap getYouHead() {
        return youHead;
    }

    public Bitmap getMyHead() {
        return myHead;
    }

    public VMsgUser getVMsgUser() {
        return msgUser;
    }

    /**
     * 设置用户信息
     */
    public void setVMsgUser(VMsgUser vMsgUser) {
        Log.d("#####ChatViewModel", vMsgUser.toString());
        this.msgUser = vMsgUser;
        if(StringUtil.isEmpty(msgUser.getUid())){
            // 获取当前用户名字头像
            ResponseCallback callback = new ResponseCallback() {
                @Override
                public void onSuccess(Object res) {
                    TUser user = (TUser) res;
                    msgUser.setToname(user.getName());
                    msgUser.setToheadimg(user.getHeadimg());
                    getUserHeadImg();
                }
                @Override
                public void onFailure(OkHttpException failuer) {

                }
            };
            RequestParams params = new RequestParams();
            params.put("id", msgUser.getTouser());
            AsynRequestUtil.post(AppServer.ROOT_PATH + "/home/getTUserById", params, TUser.class, callback);

        }else {
            getUserHeadImg();
        }


    }

    /**
     * 获取用户头像
     */
    private void getUserHeadImg(){
        // 获取用户头像
        if(!StringUtil.isEmpty(msgUser.getFromheadimg())){
            ResponseCallback callback = new ResponseCallback() {
                @Override
                public void onSuccess(Object res) {
                    byte[] image = (byte[]) res;
                    youHead = BitmapFactory.decodeByteArray(image, 0, image.length);
                    you = true;
                    if(you && me){
                        initState.setValue(new Boolean(true));
                    }
                }
                @Override
                public void onFailure(OkHttpException failuer) {

                }
            };
            AsynRequestUtil.loadImg(AppServer.HEAD_IMG_PATH + msgUser.getFromheadimg(), null, callback);
        }else {
            you = true;
            if(you && me){
                initState.setValue(new Boolean(true));
            }
        }
        // 获取用户头像
        if(!StringUtil.isEmpty(msgUser.getToheadimg())){
            ResponseCallback callback = new ResponseCallback() {
                @Override
                public void onSuccess(Object res) {
                    byte[] image = (byte[]) res;
                    myHead = BitmapFactory.decodeByteArray(image, 0, image.length);
                    me = true;
                    if(you && me){
                        initState.setValue(new Boolean(true));
                    }
                }
                @Override
                public void onFailure(OkHttpException failuer) {

                }
            };
            AsynRequestUtil.loadImg(AppServer.HEAD_IMG_PATH + msgUser.getToheadimg(), null, callback);
        }else {
            me = true;
            if(you && me){
                initState.setValue(new Boolean(true));
            }
        }
    }

    /**
     * 获取未读数据
     */
    public List<VMsgUser> getUnreadMsg(){
        String fromuser = msgUser.getFromuser() + "";
        String touser = msgUser.getTouser() + "";
        // 查询数据
        List<VMsgUser> unreadList = LitePal.where("fromuser = ? and touser = ? and state = 0", fromuser, touser)
                                        .order("sendtime")
                                        .find(VMsgUser.class);
        // 更新数据
        for(int i = 0; i < unreadList.size(); i++){
            updateMsgRead(unreadList.get(i).getUid());
        }
        Log.d("####-unread", unreadList.toString());
        return unreadList;
    }

    /**
     * 更新数据为已读
     */
    public void updateMsgRead(String uid){
        VMsgUser vMsgUser = new VMsgUser();
        vMsgUser.setState(1);
        vMsgUser.updateAll("uid = ?", uid);
    }

    /**
     * 获取历史数据
     */
    public List<VMsgUser> getHistoryMsg(int num){
        String fromuser = msgUser.getFromuser() + "";
        String touser = msgUser.getTouser() + "";
        // 查询数据
        List<VMsgUser> history = LitePal
                .where("((fromuser = ? and touser = ?) or (fromuser = ? and touser = ?)) and state = 1", fromuser, touser, touser, fromuser)
                .order("sendtime desc")
                .limit(num)
                .find(VMsgUser.class);
        Log.d("####-history", history.toString());
        return  history;
    }

    /**
     * 发送消息
     */
    public VMsgUser sendMsg(String msg){
        // 创建消息对象
        VMsgUser vMsgUser = new VMsgUser();
        vMsgUser.setUid(UUID.randomUUID().toString());
        vMsgUser.setFromheadimg(msgUser.getToheadimg());
        vMsgUser.setFromname(msgUser.getToname());
        vMsgUser.setFromuser(msgUser.getTouser());
        vMsgUser.setToheadimg(msgUser.getFromheadimg());
        vMsgUser.setToname(msgUser.getFromname());
        vMsgUser.setTouser(msgUser.getFromuser());
        vMsgUser.setMsg(msg);
        vMsgUser.setSendtime(TimeUtil.getCurrDateTime());
        vMsgUser.setState(1);

        // 保存本地
        Log.d("#####save", vMsgUser.toString());
        vMsgUser.save();

        // 发送服务器
        RequestParams params = new RequestParams();
        params.put("uid", vMsgUser.getUid());
        params.put("fromuser", vMsgUser.getFromuser());
        params.put("touser", vMsgUser.getTouser());
        params.put("sendtime", vMsgUser.getSendtime());
        params.put("msg", vMsgUser.getMsg());
        AsynRequestUtil.post(AppServer.ROOT_PATH + "/notif/sendUserMsg", params, null, null);

        return vMsgUser;
    }

}
